'use strict';

    var app = angular.module('app');
    app.controller('authGroupUpdateController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster','$modal',
        function($scope, $rootScope, $state, $timeout, toaster, $modal) {
        	
        	$scope.record = {
        		status:1,
        		grouptype:0
        	};
        	
        	if($state.includes('**.update')){
                $scope.title="修改用户组授权信息";
                $scope.reset = false;//修改不允许重置
                var id = $state.params.id;
                activate(id);
            }else if($state.includes('**.create')){
            	 $scope.title="新增用户组授权";
            	 $scope.reset = true;//新增时可以重置
            }
        	
        	validate();
        	//重置表单
			$scope.resetFrom = function(){
			   $scope.record = {
	        		status:1,
	        		grouptype:0
        		}
			}
        	$scope.submit= function(){
        		
                var m = $scope.record;
               
                if(m){
                    $scope.isDisabled = true;
                    $.ajax({
        				type: 'POST',
        	            dataType: 'json',
        				contentType:'application/json;charset=UTF-8',
        				url : '/dac/authm/group/insertOrUpdate',
        				data: angular.toJson($scope.record)
        			}).then(function(){
        				if(result.httpCode ==200){//成功
                        toaster.clear('*');
                        toaster.pop('success', '', "保存成功");
                        $timeout(function(){
                            $state.go("main.authm.group.list", $state.params);
                        },2000);
                    }else{
                        toaster.clear('*');
                        toaster.pop('error', '', result.msg);
                        $scope.isDisabled = false;
                    }
        			});
                }
                
            }
        	
        	function validate(){
                jQuery('form').validate({
                	rules: {
            			floorName: {
                           required: true,
                           stringCheck:[],
                           maxLengthB:[20]
            			},
            			buildingname: {
            				required:true
             			}
                   },
                   messages: {
                	   floorName: {
                           required: '请填写楼层名称',
                           maxLengthB:"楼层名称长度过长"
                   	   },
                   	   buildingname: {
                   		required:'请选择楼栋'
                	   }
                },
                    submitHandler: function() {
                        $scope.submit();
                    }
                });
            }
        	
        	 function activate(id) {
     	        $scope.loading = true;
             	$.ajax({
             		type: 'PUT',
     				url : '/dac/authm/group/detail',
     	            dataType: 'json',
     				contentType:'application/json;charset=UTF-8',
     				data: angular.toJson({'id': id})
     			}).then(function(result) {
     				$scope.loading = false;
     				console.log(result);
     				if (result.httpCode == 200) {
     					$scope.record = result.data;
     				} else {
     					toaster.clear('*');
                        toaster.pop('error', '', result.msg);
                        $scope.isDisabled = true;
     				}
     				$scope.$apply();
     				
     			});
             }
        	 
        $scope.showDeviceList = function() {
                 var modalInstance = $modal.open({
                     templateUrl : 'dmDeviceList.html',//script标签中定义的id
                     controller : 'deviceModalCtrl',//modal对应的Controller
                     size: 'lg',
                     resolve : {
                     	items : function() {  
                             return $scope.items;  
                         }  
                     }
                 });
                 
                 modalInstance.opened.then(function() {// 模态窗口打开之后执行的函数  
                      
                 });  
                 modalInstance.result.then(function(result) { 
                 	
                 	$scope.record.deviceid = result[0];
                 	$scope.record.deviceCode = result[1];
                 	$scope.record.deviceName = result[2];
                 	$scope.record.address = result[3];
                 	
                 	
                 }, function(reason) {  
                     console.log(reason);  
                 }); 

             };
             
             $scope.showGroupList = function(){
            	 
            	 $scope.showSelTree();
             }
             
             $scope.showSelTree = function() {
                    var modalInstance = $modal.open({
                        templateUrl : 'treeSelContent.html',//script标签中定义的id
                        controller : 'treeModalCtrl',//modal对应的Controller
                        size: 'lg',
                        resolve : {
                        	items : function() {  
                                return $scope.items;  
                            }  
                        }
                    });
                    
                    modalInstance.opened.then(function() {// 模态窗口打开之后执行的函数  
                         
                    });  
                    modalInstance.result.then(function(result) { 
                    	
                    	$scope.record.groupid = result.regionid;
                    	$scope.record.groupName = result.regionname;
                    	
                    }, function(reason) {  
                        console.log(reason);  
                    }); 

                };
            
    }]);
    
    app.controller('deviceModalCtrl', function($scope, $rootScope, $modal,$modalInstance,items) {

        
        $scope.param = { };
		$scope.search = function () {
	        $scope.loading = true;
	        if($scope.pageFlag != 1){//未点击翻页
			  	   $scope.param.pageNum=1;//将页码设置为1，即跳转回第一页
			  	}else{//点击翻页
			  	   $scope.pageFlag = 2;//将开关值设置为2
			  	}
			$.ajax({
				type: 'POST',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				url : '/dac/dm/dmManager/list',
				data: angular.toJson($scope.param)
			}).then(function(result) {
		        $scope.loading = false;
				if (result.httpCode == 200) {
					$scope.pageInfo = result;
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
		}
		
		$scope.search();
		
        $scope.select = function(item) {  
        	$scope.params = [];
        	$scope.params[0]=item.deviceId;
        	$scope.params[1]=item.deviceCode;
        	$scope.params[2]=item.deviceName;
        	$scope.params[3]=item.address;
            $modalInstance.close($scope.params);   
        };  
        $scope.cancel = function() {  
            $modalInstance.dismiss('cancel');  
        }; 
        
     // 翻页
        $scope.pagination = function (page) {
              $scope.param.pageNum=page;
              $scope.pageFlag = 1;//将开关值设置为1
              $scope.search();
        };
    });
    
    app.controller('treeModalCtrl', function($scope, $rootScope, $modal,$modalInstance,items) {

    	$scope.getTreeList=function(){ 
       	 $.ajax({
   				type: 'POST',
   	            dataType: 'json',
   				contentType:'application/json;charset=UTF-8',
   				url : '/dac/regionManage/region/tree',
   				data: angular.toJson($scope.param)
   			}).then(callback);
       	 
       	 function callback(result) {
   			
   			 if(result.httpCode ==200){//成功
                       $scope.angularTreeList=[];  
                       //查询树  
                       $scope.orgTypeList=result.data;    
                       //创建根节点  
                       var root={};  
                       root.regionname="区域管理";  
                       root.level=0;  
                       root.sequence=1;  
                       root.parentid=0;  
                       root.regionid="0";  
                       root.children=result.data;  
                       $scope.angularTreeList.push(root);  
                       $scope.treeOptions.data=$scope.angularTreeList;  
//                       toaster.clear('*');
//                       toaster.pop('success', '', "加载成功");
                       $scope.$apply();
                   }else{
//                       toaster.clear('*');
//                       toaster.pop('error', '', result.msg);
                       $scope.isDisabled = false;
                   }
   			 
               }
       	
       }  
    	
    	
    	$scope.treeOptions = {  
    	        //拖拽操作 拖拽后会返回callback beforeDrop函数，我们可以重写这个函数，拖拽本质上是顺序的改变和层级的改变，所以是一个update操作  
    	        beforeDrop : function (e) {  
    	           var source = e.source.nodeScope.item;  
    	           var destRoot = e.dest.nodesScope.item ;  
    	           if(destRoot==undefined){  
    	               return $q.reject();  
    	           }  
    	           var destIndex=e.dest.index;  
    	           var dest=e.dest.nodesScope.item.children[destIndex];  
    	           if(dest==undefined){  
    	               return $q.reject();  
    	           }  
    	           if (source.parentTypeId!=dest.parentTypeId) {         
    	               return $q.reject();  
    	           }  
    	           var sourceSeq=source.sequence;  
    	           var destSeq=dest.sequence;  
    	           source.sequence=destSeq;  
    	           dest.sequence=sourceSeq;  
    	           return;  
    	        }  
    	   };
    	
    	$scope.getTreeList();
    	
    	$scope.selectRegion = function(regionid,regionname){
    		console.log('regionid:'+regionid+',regionname'+regionname);
    		$scope.params = {};
    		$scope.params.regionid = regionid;
    		$scope.params.regionname = regionname;
    		$modalInstance.close($scope.params);   
    	}
    	
    	$scope.cancel = function() {  
            $modalInstance.dismiss('cancel');  
        }; 
    });